package cn.lixu.user.controller;

import cn.lixu.basic.exception.BusinessException;
import cn.lixu.basic.util.JsonResult;
import cn.lixu.basic.util.PageList;
import cn.lixu.user.domain.User;
import cn.lixu.user.dto.RegisterDto;
import cn.lixu.user.query.UserQuery;
import cn.lixu.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //controller层  返回的是json格式数据
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService UserService;


    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping
    public List<User> loadAll() {
        return UserService.loadAll();
    }

    /**
     * 查询一个
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User loadById(@PathVariable("id") Long id) {
        return UserService.loadById(id);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult deleteById(@PathVariable("id") Long id) {
        try {
            UserService.remove(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }

    /**
     * @param User
     * @return
     */
    @PutMapping
    public JsonResult addAndUpdate(@RequestBody User User) {
        try {
            if (User.getId() == null) {
                UserService.save(User);
            } else {
                UserService.update(User);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 分页数据
     *
     * @param UserQuery
     * @return
     */
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery UserQuery) {
        System.out.println(UserService.queryPage(UserQuery));
        return UserService.queryPage(UserQuery);

    }

    /**
     * 批量删除
     *
     * @param
     * @return
     */
    @PatchMapping
    public JsonResult patchDel(@RequestBody List<Long> ids) {
        try {
            UserService.patchDel(ids);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }

    /**
     * 手机验证码注册
     *
     * @param dto
     * @return
     */
    @PostMapping("/phoneRegister")
    public JsonResult phoneRegister(@RequestBody RegisterDto dto) {
        try {
            UserService.phoneRegister(dto);
            return JsonResult.me();
        } catch (BusinessException e) {//业务异常
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {//500
            return JsonResult.me().setMsg("网络异常，稍候重试");
        }
    }
}

